package cc.rengu.redp.bizimpl.upmp.controller;


import cc.rengu.redp.bizimpl.bean.LabelValueBean;
import cc.rengu.redp.bizimpl.enums.ChannelTypeEnum;
import cc.rengu.redp.bizimpl.enums.UserTypeEnum;
import cc.rengu.redp.bizimpl.manager.UpmpUserManager;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpMenu;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpUserInfo;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpMenuService;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpMenuVO;
import cc.rengu.redp.bizimpl.utils.EnumUtils;
import cc.rengu.redp.common.annotation.Log;
import cc.rengu.redp.common.controller.BaseController;
import cc.rengu.redp.base.domain.router.VueRouter;
import cc.rengu.redp.common.domain.QueryRequest;
import cc.rengu.redp.common.domain.RedpResponse;
import cc.rengu.redp.common.exception.RedpException;
import cc.rengu.redp.common.utils.HttpContextUtil;
import com.alibaba.druid.util.HttpClientUtils;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.google.common.collect.Lists;
import com.wuwenze.poi.ExcelKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author System
 */
@RestController
@RequestMapping("/admin/upmpmenu")
@Slf4j
public class UpmpMenuController extends BaseController {

    @Autowired
    private UpmpUserManager upmpUserManager;
    @Autowired
    private IUpmpMenuService upmpMenuService;

    @GetMapping("/{instId}/{userType}/{loginId}")
    public ArrayList<VueRouter<UpmpMenu>> getUserRouters(@NotBlank(message = "{required}") @PathVariable String instId,
                                                         @NotBlank(message = "{required}") @PathVariable String userType,
                                                         @NotBlank(message = "{required}") @PathVariable String loginId) throws Exception {
        UpmpUserInfo user=upmpUserManager.getUser(instId, userType, loginId);
        if(!ObjectUtils.isEmpty(user)){
            HttpServletRequest request = HttpContextUtil.getHttpServletRequest();
            ChannelTypeEnum channelType = upmpMenuService.getChannel(userType,request);
            if(!ChannelTypeEnum.UPMP.getType().equals(channelType.getType())
                    &&ChannelTypeEnum.BSPS_PC.getType().equals(channelType.getType())
                    &&ChannelTypeEnum.MALL_PC.getType().equals(channelType.getType())){
                throw new RedpException("不支持该终端访问！");
            }
            user.setChannelType(channelType.getType());
            return this.upmpUserManager.getUserRouters(user.getId(),channelType.getType());
        }
        return null;
    }

    /**
     * 查询数据列表
     * @param menu
     * @return
     */
    @GetMapping
//    @RequiresPermissions("menu:list")
    public Map<String, Object> menuTreeList(UpmpMenuVO menu) {
        return this.upmpMenuService.findMenus(menu);
    }

    /**
     * 查询数据列表
     * @param menu
     * @return
     */
    @GetMapping("/permsPageList")
//    @RequiresPermissions("menu:list")
    public Map<String, Object> permsPageList(QueryRequest queryRequest, UpmpMenuVO menu) throws RedpException {
        return getDataTable(this.upmpMenuService.findPermsPageList(menu,queryRequest));
    }

    /**
     * 查询数据列表
     * @param menu
     * @return
     */
    @GetMapping("/permsPrivilegePageList")
//    @RequiresPermissions("menu:list")
    public Map<String, Object> permsPrivilegePageList(QueryRequest queryRequest, UpmpMenuVO menu) throws RedpException {

        if(StringUtils.isEmpty(menu.getChannelType())){
            throw new RedpException("请输入所属渠道分类");
        }
        return getDataTable(this.upmpMenuService.permsPrivilegePageList(menu,queryRequest));
    }

    @Log("新增菜单/按钮")
    @PostMapping
    @RequiresPermissions("menu:add")
    public RedpResponse addMenu(@Valid UpmpMenu menu) throws RedpException {
        try {
            this.upmpMenuService.createMenu(menu);
        } catch (Exception e) {
            String message = "新增菜单/按钮失败";
            log.error(message, e);
            return RedpResponse.getInstance().failure().message(message);
        }
        return RedpResponse.getInstance().success().message("新增菜单/按钮成功");
    }

    @Log("删除菜单/按钮")
    @DeleteMapping("/{menuIds}")
    @RequiresPermissions("menu:delete")
    public RedpResponse deleteMenus(@NotBlank(message = "{required}") @PathVariable String menuIds) throws RedpException {
        try {
            String[] ids = menuIds.split(StringPool.COMMA);
            this.upmpMenuService.deleteMeuns(ids);
        } catch (Exception e) {
            String message = "删除菜单/按钮失败";
            log.error(message, e);
            return RedpResponse.getInstance().failure().message(message);
        }
        return RedpResponse.getInstance().success().message("删除菜单/按钮成功");
    }

    @Log("修改菜单/按钮")
    @PutMapping
    @RequiresPermissions("menu:update")
    public RedpResponse updateMenu(@Valid UpmpMenu menu) throws RedpException {
        try {
            this.upmpMenuService.updateMenu(menu);
        } catch (Exception e) {
            String message = "修改菜单/按钮失败";
            log.error(message, e);
            return RedpResponse.getInstance().failure().message(message);
        }
        return RedpResponse.getInstance().success().message("删除菜单/按钮成功");
    }

    @PostMapping("excel")
    @RequiresPermissions("menu:export")
    public void export(UpmpMenuVO menu, HttpServletResponse response) throws RedpException {
        try {
            List<UpmpMenu> menus = this.upmpMenuService.findMenuList(menu);
            ExcelKit.$Export(UpmpMenu.class, response).downXlsx(menus, false);
        } catch (Exception e) {
            String message = "导出Excel失败";
            log.error(message, e);
            throw new RedpException(message);
        }
    }


    @GetMapping("getChannelType")
    @RequiresPermissions(value = {"menu:add","menu:update"},logical = Logical.OR)
    public List<LabelValueBean> getAll() throws RedpException {
        List<LabelValueBean> result = Lists.newArrayList();
        LabelValueBean firt = new LabelValueBean("","请选择");
        result.add(firt);
        result.addAll( EnumUtils.getEnumToListBean(ChannelTypeEnum.class));
        return result;
    }
}
